import ArticleItem from '@/components/ArticleItem';
import styles from './index.module.scss';
import { useAppDispatch, useAppSelector } from '@/store';
import { map } from 'lodash';
import { ArticleResult } from '@/store/reducer/article';
import { useEffect } from 'react';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { getArticleAction, refreshArticleAction } from '@/store/action/article';
type Props = {
  channel_id: number;
  style?: any;
};

export default function ArticleList({ channel_id, style }: Props) {
  const dispatch = useAppDispatch();
  const { articleData } = useAppSelector((state) => state.article);
  const data = (articleData[channel_id] || {}).results;
  const pre_timestamp = (articleData[channel_id] || {}).pre_timestamp;

  useEffect(() => {
    // 1553788800000
    dispatch(getArticleAction(channel_id, 1553788800000));
  }, [dispatch, channel_id]);
  //上拉加载更多
  const loadMore = async () => {
    await dispatch(getArticleAction(channel_id, Number(pre_timestamp)));
  };
  return (
    <div className={styles.root}>
      <div className="channel-list" style={{ ...style }}>
        <PullToRefresh
          onRefresh={async () => {
            await dispatch(refreshArticleAction(channel_id));
          }}
        >
          {map(data, (item: ArticleResult) => (
            <ArticleItem key={item.art_id} data={item} />
          ))}
        </PullToRefresh>

        {!!data?.length && (
          <InfiniteScroll
            loadMore={loadMore}
            // 存储数据的数组长度小于总数时，才会触发加载更多
            hasMore={pre_timestamp ? true : false}
          ></InfiniteScroll>
        )}
      </div>
    </div>
  );
}
